<template>
  <div class="maintenance-add">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>添加维护记录</span>
          <el-button @click="$router.go(-1)">返回</el-button>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px" 
        class="maintenance-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产选择" prop="assetId">
              <el-select 
                v-model="form.assetId" 
                placeholder="请选择资产"
                filterable
                remote
                :remote-method="searchAssets"
                :loading="assetLoading"
              >
                <el-option
                  v-for="asset in assetOptions"
                  :key="asset.id"
                  :label="`${asset.name} (${asset.code})`"
                  :value="asset.id"
                >
                  <span>{{ asset.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ asset.code }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择维护类型">
                <el-option label="定期维护" value="定期维护"></el-option>
                <el-option label="故障维修" value="故障维修"></el-option>
                <el-option label="预防性维护" value="预防性维护"></el-option>
                <el-option label="紧急维修" value="紧急维修"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维护人员" prop="maintainer">
              <el-select v-model="form.maintainer" placeholder="请选择维护人员" filterable>
                  <el-option
                    v-for="m in maintainerOptions"
                    :key="m.id"
                    :label="m.name"
                    :value="m.id"
                  />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级">
                <el-option label="低" value="低"></el-option>
                <el-option label="中" value="中"></el-option>
                <el-option label="高" value="高"></el-option>
                <el-option label="紧急" value="紧急"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划日期" prop="planDate">
              <el-date-picker
                v-model="form.planDate"
                type="date"
                placeholder="选择计划日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预估费用" prop="estimatedCost">
              <el-input-number
                v-model="form.estimatedCost"
                :min="0"
                :precision="2"
                :step="100"
                placeholder="请输入预估费用"
              />
              <span class="unit">元</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="维护描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述维护内容、要求等"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <!-- 暂时隐藏文件上传功能 -->
        <!--
        <el-form-item label="附件上传">
          <el-upload
            ref="uploadRef"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            multiple
            :limit="5"
            :file-list="fileList"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png/pdf/doc/docx格式，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        -->
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            提交
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, UploadProps } from 'element-plus'
import { assetApi, maintenanceApi, userApi } from '@/api'
import { MaintStatusTextToCode } from '@/utils/status'

const router = useRouter()
const formRef = ref<FormInstance>()
const uploadRef = ref()
const submitting = ref(false)
const assetLoading = ref(false)
const fileList = ref([])

// 表单数据
const form = reactive({
  assetId: '',
  type: '',
  maintainer: '',
  priority: '中',
  planDate: '',
  estimatedCost: 0,
  description: '',
  attachments: [] as { name: string; url: string }[]
})

// 资产选项动态加载
const assetOptions = ref<any[]>([])

// 维护人员选项
const maintainerOptions = ref<any[]>([])

// 表单验证规则
const rules = {
  assetId: [
    { required: true, message: '请选择资产', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择维护类型', trigger: 'change' }
  ],
  maintainer: [
    { required: true, message: '请选择维护人员', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  planDate: [
    { required: true, message: '请选择计划日期', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入维护描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 上传配置
const uploadUrl = '/api/upload'
const uploadHeaders = {
  'Authorization': 'Bearer ' + localStorage.getItem('token')
}

// 搜索资产
const searchAssets = async (query: string) => {
  if (!query) {
    assetOptions.value = []
    return
  }
  assetLoading.value = true
  try {
    const res: any = await assetApi.getList({ name: query, size: 20 })
    assetOptions.value = (res.list || []).map((n: any) => ({ id: n.id, name: n.name, code: n.code }))
  } finally {
    assetLoading.value = false
  }
}

// 预加载维护人员
const loadMaintainers = async () => {
  try {
    const users: any = await userApi.getAll()
    maintainerOptions.value = (users || []).map((u: any) => ({ id: u.id, name: u.fullName || u.username }))
  } catch (e) {
    console.error('加载维护人员失败', e)
  }
}

onMounted(() => {
  loadMaintainers()
})

// 禁用日期（不能选择过去的日期）
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 文件上传前验证
const beforeUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf', 
    'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/PDF/DOC/DOCX 格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess: UploadProps['onSuccess'] = (response, file) => {
  ElMessage.success('文件上传成功')
  form.attachments.push({
    name: file.name,
    url: response.data.url
  })
}

// 上传失败
const handleUploadError: UploadProps['onError'] = () => {
  ElMessage.error('文件上传失败')
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 将日期转换为后端期望的格式：yyyy-MM-dd HH:mm:ss
    let scheduledTimeFormatted = null
    if (form.planDate) {
      const date = new Date(form.planDate)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      scheduledTimeFormatted = `${year}-${month}-${day} 00:00:00`
    }

    // 组装后端期望字段
    const priorityMap:{[k:string]:number}={ '高':1,'中':2,'低':3,'紧急':4 }
    const today = new Date().toISOString().slice(0, 10)
    const payload = {
      assetId: form.assetId,
      maintDate: form.planDate,          // 数据库必填列
      startDate: today,                  // 开始日期 = 当前日期
      endDate: form.planDate,            // 计划日期作为结束日期
      type: form.type,
      priority: priorityMap[form.priority] || 2,
      status: 0,                         // 待维护
      description: form.description,
      performedBy: form.maintainer || null,
      cost: form.estimatedCost
    }

    await maintenanceApi.add(payload)
    ElMessage.success('维护记录添加成功')
    router.push('/maintenance/list')
  } catch(error) {
    console.error('提交维护记录失败:', error)
    ElMessage.error('提交失败，请检查表单')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  form.attachments = []
  fileList.value = []
}
</script>

<style scoped>
.maintenance-add {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.maintenance-form {
  max-width: 800px;
  margin: 0 auto;
}

.unit {
  margin-left: 10px;
  color: var(--text-color-secondary);
}

@media (max-width: 768px) {
  .maintenance-add {
    padding: 10px;
  }
  
  .maintenance-form {
    max-width: 100%;
  }
}
</style> 